package com.neasho.neashoadminv1.infrastructure.framework

import com.neasho.neashoadminv1.infrastructure.domain.R
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice

/**
 * 校验错误
 */

@RestControllerAdvice
class ValidationAdvice {
    @ExceptionHandler(MethodArgumentNotValidException::class)
    fun handleValidationExceptions(ex: MethodArgumentNotValidException): ResponseEntity<R<List<String?>>> {
        val errors = ex.bindingResult.allErrors.map { it.defaultMessage }
        val retObj = R.error<List<String?>>(HttpStatus.BAD_REQUEST.value(), "请求参数错误")
            .also { it.data = errors }
        return ResponseEntity.badRequest()
            .body(retObj)
    }
}